package com.sky.loveshop.job;

import cn.hutool.core.collection.CollectionUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.sky.loveshop.entity.OrderDetail;
import com.sky.loveshop.entity.OrderInfo;
import com.sky.loveshop.entity.qo.StockParam;
import com.sky.loveshop.service.IotService;
import com.sky.loveshop.service.OrderDetailService;
import com.sky.loveshop.service.OrderInfoService;
import com.sky.loveshop.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/9/1 22:34
 */
@Slf4j
@Service
public class PaymentJob {

    @Resource
    private AlipayClient alipayClient;
    @Resource
    private OrderInfoService orderInfoService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private SkuService skuService;
    @Resource
    private IotService iotService;

    @Scheduled(fixedRate = 15000)   // 每 15 秒检查一次订单支付状态
    public void checkOrderPaymentStatus() {
        // 查询未支付的订单,并调用支付宝统一订单查询接口检查支付状态
        List<String> unPayOrders = getUnPayOrders();
        if (CollectionUtil.isEmpty(unPayOrders)) {
            return;
        }

        for (String orderNo : unPayOrders) {
            updateOrderStatus(orderNo);
        }
    }

    /**
     * 已经支付则更新订单状态为已支付，未支付则主动查询订单状态次数+1
     * @param orderNo
     * @return
     */
    public void updateOrderStatus(String orderNo) {

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(orderNo);
        request.setBizModel(model);
        try {
            AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
            if (response.isSuccess() && "TRADE_SUCCESS".equals(response.getTradeStatus())) {
                String tradeNo = response.getTradeNo();
                String buyerUserId = response.getBuyerUserId();
                log.info("{} 已支付", orderNo);
                // 更新订单状态为已支付
                updateOrderStatus(orderNo, tradeNo, buyerUserId);
            } else {
                log.info("{} 未支付", orderNo);
                // 更新订单主动查询支付结果次数+1
                updateOrderQueryTimes(orderNo);
            }
        } catch (Exception e) {
            log.error("updateOrderStatusError 主动查询订单支付结果异常", e);
            e.printStackTrace();
        }

        //使用json格式发起请求，非证书模式请求 使用execute方法，证书模式使用certificateExecute方法
        //AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        //request.setBizContent("{\"out_trade_no\":\"" + orderNo + "\"}");
        //try {
        //    AlipayTradeQueryResponse response = alipayClient.execute(request);
        //    if (response.isSuccess() && "TRADE_SUCCESS".equals(response.getTradeStatus())) {
        //        // 更新订单状态为已支付
        //        updateOrderStatus(orderNo, true);
        //        return true;
        //    } else {
        //        return false;
        //    }
        //} catch (Exception e) {
        //    e.printStackTrace();
        //    return false;
        //}
    }

    /**
     * 主动查询到订单支付未成功,将主动查询订单次数+1
     * @param orderNo
     */
    private void updateOrderQueryTimes(String orderNo) {
        orderInfoService.updateOrderQueryTimes(orderNo);
    }

    /**
     * 获取未支付的订单
     * @return
     */
    private List<String> getUnPayOrders() {
        // 获取已经主动查询12次(1分钟内每5秒主动查一次) 支付状态仍旧是未支付的订单
        List<OrderInfo> unPayOrderList = orderInfoService.getUnPayOrderList();
        if (CollectionUtil.isNotEmpty(unPayOrderList)) {
            List<String> unPayOrderNoList = unPayOrderList.stream().map(OrderInfo::getOrderNo).collect(Collectors.toList());
            return unPayOrderNoList;
        }
        return null;
    }

    /**
     * 主动查询到订单支付成功,将订单状态变更为1 支付成功
     * @param orderNo
     */
    private void updateOrderStatus(String orderNo, String tradeNo, String buyerUserId) {
        // 更新订单状态的逻辑
        OrderInfo orderInfo = orderInfoService.getOrderInfoByOrderNo(orderNo);
        if (orderInfo.getOrderStatus() == 1) {
            log.info("订单状态已经是已支付状态,无需再次更新 {} {}", orderNo, tradeNo);
        }
        orderInfo.setOrderStatus(1);
        orderInfo.setTradeNo(tradeNo);
        orderInfo.setBuyerUserId(buyerUserId);
        orderInfo.setUpdateTime(new Date());
        orderInfoService.updateOrderStatus(orderInfo);

        // 扣减库存
        List<OrderDetail> orderDetails = orderDetailService.getDetailListByOrderId(orderInfo.getId());
        for(OrderDetail o : orderDetails){
            StockParam param = new StockParam();
            param.setUserId(9999);
            param.setType(0);
            param.setNum(o.getNum());
            param.setSkuId(o.getSkuId());
            skuService.changeStockNum(param);
        }

        // 调用远程开门指令
        try {
            String s = iotService.openDoorAfterPay(orderInfo.getShopId());
            log.info("openDoorAfterPayByJob 支付成功后开门成功  shopId:{} result:{}", orderInfo.getShopId(), s);
        } catch (Exception e) {
            log.error("openDoorAfterPayByJob 支付成功后开门失败 shopId:{}", orderInfo.getShopId(), e);
        }

    }
}
